﻿@inject IJSRuntime JSRuntime
@inject StateService State
@inject NavigationManager Navigation
@inject IHttpClientFactory HttpClientFactory
@inject AuthenticationStateProvider AuthStateProvider
@inject Blazored.LocalStorage.ILocalStorageService localStorage
@using Shared.Model
@using System.ComponentModel.DataAnnotations;
@using System.ComponentModel
@using System.Reflection
@using System.Text.Json
@using Shared.Service

<Form Model="@loginModel"
OnFinish="OnFinish"
OnFinishFailed="OnFinishFailed"
LabelColSpan="8"
WrapperColSpan="16"
ValidateOnChange>

    @foreach (var field in fields)
    {
        @if (field.Key != "Password")
        {
            <FormItem Name="@field.Key">
                @InputRender(field.Value)
            </FormItem>
        }else
        {
            <FormItem Name="@field.Key">
                <InputPassword @bind-Value="context.Password">
                    <!--<Prefix><Icon Type="user" /></Prefix>-->
                </InputPassword>
            </FormItem>

        }

    }
    <FormItem WrapperColOffset="8" WrapperColSpan="16">
        <Button Type="ButtonType.Primary" HtmlType="submit">
            登录
        </Button>
    </FormItem>
</Form>

@code {
    private Dictionary<string, PropertyInfo> fields = new();
    private LoginModel loginModel { get; set; } = new LoginModel();

    // Ant Design Components
    AntDesign.Form<LoginModel> loginForm;
    [Parameter]
    public bool IsLoginFailed { get; set; }
    [Parameter]
    public EventCallback OnLoginFailed { get; set; }

    protected override void OnInitialized()
    {
        // 通知状态变化
        State.OnStateChange += StateHasChanged;
        fields = typeof(LoginModel).GetProperties().ToDictionary(x => x.Name, x => x);
        base.OnInitialized();
    }
    public void Dispose()
    {
        State.OnStateChange -= StateHasChanged;
    }

    private RenderFragment InputRender(PropertyInfo property)
    {
        return property switch
        {
            //_ when property.PropertyType.GetCustomAttribute<DataTypeAttribute>()?.DataType == DataType.Password =>@<InputPassword></InputPassword>,
            _ when property.PropertyType == typeof(bool) =>@<Checkbox></Checkbox>,
            _ when property.PropertyType == typeof(DateOnly?) =>@<DatePicker TValue="DateOnly?"></DatePicker>,
            _ =>@<Input TValue="string"></Input>,
        };
    }

    private async Task OnFinish(EditContext editContext)
    {
        try
        {
            using (var client = HttpClientFactory.CreateClient("ServerApi"))
            {
                var response = await client.PostAsJsonAsync("/api/Auth/login", loginModel);

                if (response.IsSuccessStatusCode)
                {
                    // Parse JWT
                    var loginResponse = await response.Content.ReadFromJsonAsync<LoginResponse>();
                    if (!string.IsNullOrEmpty(loginResponse.Token))
                    {
                        // 将 JWT 存储到 localStorage
                        await localStorage.SetItemAsync("jwtToken", loginResponse.Token);
                        Console.WriteLine($"Stored token: {loginResponse.Token}"); // Debugging
                        // 跳转到主页
                        ((CustomAuthStateProvider)AuthStateProvider).MarkUserAsAuthenticated(loginResponse.Token);
                        // Find User Id State.CurrentUserId =
                        // Wait For Implement
                        State.CurrentUserName = loginModel.Username;
                        Navigation.NavigateTo("/home");
                    }
                    else
                    {
                        await NotifyLoginFailed();
                        Console.WriteLine("登录失败：未收到有效的 Token");
                    }
                }
                else
                {
                    await NotifyLoginFailed();
                    Console.WriteLine("登录失败：用户名或密码错误");
                }
            }
            // 调用服务端登录 API
            
        }
        catch (Exception ex)
        {
            await NotifyLoginFailed();
            Console.WriteLine($"登录请求出错: {ex.Message}");
        }
    }

    private async void OnFinishFailed(EditContext editContext)
    {
        await NotifyLoginFailed(); // 显示 Alert
        Console.WriteLine($"Failed:{JsonSerializer.Serialize(loginModel)}");
    }

    private async Task NotifyLoginFailed()
    {
        if (OnLoginFailed.HasDelegate)
        {
            await OnLoginFailed.InvokeAsync(); // 通知父组件登录失败
        }
    }
}